import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { RoleService } from 'src/app/services/role.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { PageTitleService } from 'src/app/services/page-title.service';
interface Person {
  key: string;
  name: string;
  sex: string,
  creationTime: string,
  unit: string,
  status: string;
}

@Component({
  selector: 'zepride-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.less']
})
export class RoleComponent implements OnInit {
  listOfData = [];
  permitssList = [];
  loading = true;
  total = 1;
  selectedValue = null;
  isRoleVisible = false;
  params = {
    name: '',
    pageIndex: 1,
    countOfPage: 10
  };
  roleParams = {
    id: '0',
    name: '',
    description: '',
    status: '0',
    isGlobal: false,
    createTime: new Date().getTime(),
    organizationId: this.roleService.orgid,
    isDelete: false,
    permits: []
  };
  constructor(
    private route: Router,
    private modal: NzModalService,
    private roleService: RoleService,
    private msg: NzMessageService,
    private phSvr: PageTitleService,
  ) {
    this.phSvr.setPageHeaderOption({
      title: '角色信息',
      subTitle: '用于添加机构管理的角色信息',
      buttons: [
        {
          text: '添加角色',
          ngType: 'primary',
          icon: "plus-circle",
          onClick: () => {
            this.addEditData(0, '', 'add');
          }
        },
      ]
    });
  }
  ngOnInit(): void {
    this.getData();
    this.queryAccountPermitss('');
  }
  async getData() {
    this.loading = true;
    try {
      const data = await this.roleService.queryRoles(this.params);
      this.listOfData = data.list;
      this.total = data.total;
      this.loading = false;
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  async queryAccountPermitss(Id) {
    try {
      const data = await this.roleService.queryAccountPermitss({ authObjectId: Id, authObjectType: 'Role' });

      //newArr 添加状态
      const newArr = data.permitConfig.map(v => {
        return { ...v, checked: false }
      })
      // //判断list 是否有值，有值代表有权限
      if (data.list.length) {
        data.permitConfig.filter(p => {
          data.list.find(i => {
            if (p.permitId == i.permitId) {
              return p.checked = true;
            }
          })
        })
        //插入保存数据this.roleParams.permits
        this.roleParams.permits = data.list.map(v => {
          return { permitId: v.permitId, permitName: v.permitName }
        })
      }
      // 遍历数据格式
      const result = [];
      data.permitConfig.forEach((item) => {
        var { groupName } = item;
        if (!result[groupName]) {
          result[groupName] = {
            groupName,
            value: []
          }
        }
        result[groupName].value.push({ permitId: item.permitId, permitName: item.permitName, checked: item.checked });
      });

      this.permitssList = Object.values(result);
      this.permitssList.forEach(element => {
        this.isCheckAll(element);
      });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  clear() {
    this.params.name = '';
    this.params.pageIndex = 1;
    this.onSearch();
  }
  onSearch() {
    this.params.pageIndex = 1;
    this.getData();
  }
  changePageIndex(pageIndex) {
    this.params.pageIndex = pageIndex;
    this.getData();
  }
  changePageSize(pageSize) {
    this.params.countOfPage = pageSize;
    this.getData();
  }
  async confirmInfo() {
    if (!this.roleParams.name) {
      this.msg.create('error', '请填写角色名称');
      return;
    }
    if ((/.*\S.*/).test(this.roleParams.name) == false) {
      this.msg.create('error', '角色名称不能全为空格');
      return;
    }
    //清空值
    this.roleParams.permits = [];
    // push选中得数据
    this.permitssList.forEach(element => {
      element.value.forEach(element2 => {
        if (element2.checked) {
          this.roleParams.permits.push({
            permitId: element2.permitId,
            permitName: element2.permitName,
          });
        }
      });
    });
    if (!this.roleParams.permits.length) {
      this.msg.create('error', '请选择角色权限');
      return;
    }
    try {
      //添加
      if (this.roleParams.id == '0') {
        const data = await this.roleService.createRole(this.roleParams);
        //编辑
      } else {
        const data = await this.roleService.updateRole(this.roleParams);
      }

      this.msg.success(this.roleParams.id == '0' ? '添加角色成功' : '编辑角色成功');
      this.isRoleVisible = false;
      //查询列表
      this.getData();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }


  }
  async addEditData(Id, name, type) {
    if (type != 'details') {
      this.queryAccountPermitss(Id);
      this.isRoleVisible = true;
      this.roleParams.name = name;
      this.roleParams.id = Id;
      if (type == 'add') {
        this.roleParams.permits = [];
      }
    } else {
      this.route.navigate(['/home/detailsRole'], { queryParams: { Id: Id } });
    }
  }
  delListItem(id, name, i) {
    this.modal.confirm({
      nzTitle: `您确定要删除<b style="color: red;">${name}</b>么?`,
      nzOnOk: () => {
        this.deleteUser(id, i);
      }
    });
  }
  checkAllLog(permitssList) {
    permitssList.value.forEach(e => {
      e.checked = permitssList.checked;
    });
  }
  isCheckAll(permitssList) {
    permitssList.checked = permitssList.value.every(v => v.checked);
  }
  checkboxLog(item, permitssList): void {
    if (!item.checked) {
      permitssList.checked = false;
    } else {
      this.isCheckAll(permitssList);
    }
  }
  clickStatus(item) {
    this.modal.confirm({
      nzTitle: `您确定要${item.status == 0 ? '禁用' : '启用'}么?`,
      nzOnOk: () => {
        this.updatePersonnel(item);
      }
    });
  }
  async updatePersonnel(item) {
    item.status = item.status == 0 ? '1' : '0';
    try {
      await this.roleService.updateRole(item);

      this.msg.success(`${item.status == 0 ? '启用' : '禁用'}成功`);
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  //删除角色
  async deleteUser(id, i) {
    try {
      await this.roleService.deleteRole(id);
      this.msg.success('删除角色成功');
      this.getData();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

}
